package com.dd.cloud.common.utils;

import org.apache.commons.io.FilenameUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Base64;

/**
 * @author Lx
 * @version 1.0
 */
public class ImageUtils {
    /**
     * 图片url转base64
     *
     * @param url
     * @return
     */
    public static String imageUrlToBase64(String url) {
        BufferedImage image;
        try {
            image = ImageIO.read(new URL(url));
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, FilenameUtils.getExtension(url), outStream);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        byte[] byteArr = outStream.toByteArray();
        return Base64.getEncoder().encodeToString(byteArr);
    }
}
